package com.imaker.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imaker.dao.BaseDao;
import com.imaker.domain.RoleActionOperateInfo;
import com.imaker.domain.RoleInfo;
import com.imaker.domain.UserRoleInfo;
import com.imaker.utils.CacheUtils;
import com.imaker.vo.CacheInfo;

 /**
 * <p>程序名称：       CacheService.java</p>
 * <p>程序说明：       TODO</p>
 * <p>版权信息：       Copyright mayonghua</p>
 * 
 * @author：          mayonghua
 * @version：         Ver 0.1
 */
@Service
public class CacheService implements IService {
	private BaseDao<RoleInfo> roleDAO = null;
	private BaseDao<UserRoleInfo> userRoleDAO = null;
	private BaseDao<RoleActionOperateInfo> roleActionOperateDAO = null;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		roleDAO = new BaseDao<RoleInfo>(sessionFactory,RoleInfo.class);
		userRoleDAO = new BaseDao<UserRoleInfo>(sessionFactory,UserRoleInfo.class);
		roleActionOperateDAO = new BaseDao<RoleActionOperateInfo>(sessionFactory,RoleActionOperateInfo.class);
	}
	
	/**
	 * 往系统中添加缓存
	 */
	public void refreshCache(String id) throws Exception{
		//根据用户获得角色
		List<UserRoleInfo> userRoleList = userRoleDAO.findByProperty("user.id", id);
		//设置缓存的内容
		CacheInfo cacheInfo = new CacheInfo();
		cacheInfo.setOperate(roleOperate(userRoleList));
		//根据用户id进行缓存刷新
		CacheUtils.put("ROLEOPERATE",id, cacheInfo);
	}
	
	public Map<String,String> roleOperate(List<UserRoleInfo> userRoleList) throws Exception{
		
		Map<String,String> operateMap = new HashMap<String,String>();
		if(userRoleList!=null&&userRoleList.size()>0){
			for(UserRoleInfo ur : userRoleList){
				//根据角色获得该用户的可操作数据
				List<RoleActionOperateInfo> roleActionOperateList = roleActionOperateDAO.findByProperty("role.id", ur.getRole().getId());
				//将角色数据转换为MAP
				for(RoleActionOperateInfo raoi : roleActionOperateList){
					operateMap.put(raoi.getWebId(), raoi.getState());
				}
			}
		
		}
		return operateMap;
	}
}
